/*
* 数据缓存管理
* */
import 'dart:convert';
import 'package:lighthouse/index.dart';

class PermissionCache {
  static const String _keyStr = "permission";

  // 单例公开访问点
  factory PermissionCache() => _sharedInstance();

  // 静态私有成员，没有初始化
  static PermissionCache? _instance;

  // 私有构造函数
  PermissionCache._() {
    // 具体初始化代码
  }

  // 静态、同步、私有访问点
  static PermissionCache _sharedInstance() {
    return _instance ??= PermissionCache._();
  }

  late bool _isLoadData = false;

  /*当前网络数据*/
  List<Permission>? _netData;

  /*历史缓存数据*/
  List<Permission>? _cacheData;

  /*加载网络数据*/
  Future loadNetData(BuildContext context) async {
    if (!_isLoadData) {
      _isLoadData = true;
      try {
        ResponseData<List<Permission>> responseData =
            await Api(context).getPermission();
        _netData = responseData.dataModel;
        //保存数据
        if (responseData.success) {
          Global.getPrefs().setString(_keyStr, jsonEncode(responseData.data));
        }
      } catch (e) {
        Debug.info(e.toString());
        _isLoadData = false;
        if (e is DioError) {
          //登录失败则提示
          showToast(e.response?.statusMessage ?? S.of(context).networkError);
        } else if (e is Error) {
          Debug.info(e.stackTrace.toString());
        }
      } finally {
        // 隐藏loading框
        // Navigator.of(context).pop();
      }

    }
    return _isLoadData;
  }

  /*获取当前数据*/
  List<Permission>? getCurrentData() {
    List<Permission>? mData;
    if (_netData != null) {
      // 如果有请求的数据 就返回请求的数据
      mData = _netData;
    } else if (_cacheData == null) {
      // 设置缓存数据
      var _cacheStr = Global.getPrefs().getString(_keyStr);
      if (_cacheStr != null) {
        try {
          mData = _cacheData = jsonDecode(_cacheStr)
              .map<Permission>((e) => Permission.fromJson(e))
              .toList();
        } on Error catch (e) {
          Debug.info(e.toString());
          Debug.info(e.stackTrace.toString());
        }
      }
    } else {
      mData = _cacheData;
    }
    return mData;
  }

  // /*获取根结点*/
  // Permission? getAppRootPermission() {
  //   List<Permission>? list = getCurrentData();
  //   if (list != null) {
  //     for (Permission permission in list) {
  //       if (permission.path == "app") {
  //         return permission;
  //       }
  //     }
  //   }
  //   return null;
  // }

  /*根据path获取权限*/
  Permission? getPermission(String path, {List<Permission>? list}) {
    list ??= getCurrentData();
    if (list != null) {
      for (Permission permission in list) {
        if (permission.children != null) {
          //查看是否有子节点
          Permission? childPermission =
              getPermission(path, list: permission.children);
          if (childPermission != null) {
            //如果已经遍历到则返回
            return childPermission;
          }
        }
        if (permission.path == path) {
          return permission;
        }
      }
    }
    return null;
  }
  /*根据code获取权限*/
  static Permission? getPermissionFromId(String id, List<Permission> list) {
    for (Permission permission in list) {
      if (permission.id == id) {
        return permission;
      }
    }
    return null;
  }
  //
  // /*获取当前数据*/
  // Permission? getPermission(String code) {
  //   List<Permission>? roorlist =
  //       getChildPermissionList(getCurrentData(), "app");
  //   if (list != null) {}
  //
  //   // return false;
  // }

  /*清楚数据*/
  void clearData() {
    _isLoadData = false;
    _netData = null;
    _cacheData = null;
    Global.getPrefs().remove(_keyStr);
  }
}
